<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/23
 * Time: 1:22 PM
 */
namespace app\backend\modules\sys\controllers;

use app\backend\controllers\BaseController;
use app\common\facades\Setting;
use app\common\services\AutoUpdate;
use app\common\services\QcloudCosClient;
use Ixudra\Curl\Facades\Curl;

class SettingController extends BaseController
{
    /**
     * 站点设置页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function site(){
        return view("backend.sys.setting.site");
    }

    /**
     * 站点设置数据
     * @return \Illuminate\Http\JsonResponse
     */
    public function siteInfo(){
        $setting = Setting::get('cms.site');
        $setting['site_logo'] = fmt_media_url($setting['site_logo']);
        $setting['title_icon'] = fmt_media_url($setting['title_icon']);
        $setting['advertisement'] = fmt_media_url($setting['advertisement']);
        return $this->successJson('', $setting);
    }

    /**
     * 保存站点设置
     * @return \Illuminate\Http\JsonResponse
     */
    public function siteSave(){
        $request = request()->setting;
        if ($request) {
            if (Setting::set('cms.site', $request)) {
                return $this->successJson('设置成功');
            } else {
                return $this->errorJson('设置失败');
            }
        }else{
            return $this->errorJson('参数获取失败');
        }
    }

    /**
     * 附件设置页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function attach(){
        return view("backend.sys.setting.attach");
    }

    /**
     * 附件设置信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function attachInfo(){
        $setting = Setting::get('cms.attach');
        if($setting['pic_suffix']){
            $setting['pic_suffix'] = implode("\n", $setting['pic_suffix']);
        }
        if($setting['audio_suffix']){
            $setting['audio_suffix'] = implode("\n", $setting['audio_suffix']);
        }
        return $this->successJson('', $setting);
    }

    /**
     * 保存附件设置
     * @return \Illuminate\Http\JsonResponse
     */
    public function attachSave(){
        $request = request()->setting;
        if ($request) {
            if($request['pic_suffix']){
                $request['pic_suffix'] = explode("\n", $request['pic_suffix']);
            }
            if($request['audio_suffix']){
                $request['audio_suffix'] = explode("\n", $request['audio_suffix']);
            }
            if (Setting::set('cms.attach', $request)) {
                return $this->successJson('设置成功');
            } else {
                return $this->errorJson('设置失败');
            }
        }else{
            return $this->errorJson('参数获取失败');
        }
    }
    /**
     * 远程附件设置页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function remoteAttach(){
        return view("backend.sys.setting.remote_attach");
    }
    /**
     * 远程附件设置信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function remoteAttachInfo(){
        $setting = Setting::get('cms.remote_attach');
        $res = [];
        $res['setting'] = $setting;
        $res['cos_regions'] = QcloudCosClient::getRegionList();
        return $this->successJson('', $res);
    }
    /**
     * 远程保存附件设置
     * @return \Illuminate\Http\JsonResponse
     */
    public function remoteAttachSave(){
        $request = request()->setting;
        if ($request) {
            if (Setting::set('cms.remote_attach', $request)) {
                return $this->successJson('设置成功');
            } else {
                return $this->errorJson('设置失败');
            }
        }else{
            return $this->errorJson('参数获取失败');
        }
    }

    /**
     * 系统授权设置页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function auth(){
        return view("backend.sys.setting.auth");
    }

    /**
     * 系统授权设置信息
     */
    public function authInfo(){
        $setting = Setting::get('cms.auth');
        $res = [];
        $res['setting'] = $setting;
        $res['page'] = 'auth';
        if (empty($setting['key']) && empty($setting['secret'])) {
            $domain = request()->getHttpHost();
            $auth_str = (new AutoUpdate())->checkDomain(['domain' => $domain]);

            if (empty($auth_str['data']['key']) && empty($auth_str['data']['secret'])) {
                $res['page'] = 'free';
            } else {
                $setting = $auth_str['data'];

                $this->processingKey($setting, 'create');

                $free_plugins = \app\common\models\Setting::where('group', 'free')->where('key', 'plugin')->first();

                if (!is_null($free_plugins)) {
                    Setting::set('free.plugin', unserialize($free_plugins->value));
                }
                //重新获取配置
                $res['setting'] = Setting::get('cms.auth');
            }
        }
        return $this->successJson('',$res);

    }
    /**
     * 系统授权设置保存
     */
    public function authSave(){
        $requestModel = request()->setting;
        $type = request()->type;
        //检测数据是否存在
        $res = $this->isExist();

        $auth_url = '';
        $message = $type == 'create' ? '添加' : '取消';
        //var_dump($res);exit();
        if (!$res['isExists']) {
            if ($res['message'] == 'amount exceeded') {
                $this->errorJson('您已经没有剩余站点数量了，如添加新站点，请取消之前的站点或者联系我们的客服人员！');
            } else {
                $this->errorJson('Key或者密钥出错了！');
            }

        } else {
            if ($this->processingKey($requestModel, $type)) {
                return $this->successJson("站点{$message}成功", ['url' => $auth_url]);
            } else {
                $this->errorJson("站点{$message}失败");
            }
        }
    }

    /**
     * 系统授权注册
     */
    public function authRegister(){
        $data = request()->data;

        $auth_url = absolute_admin_url('sys.setting.auth');
        $params = [
            'domain'=>request()->getHttpHost(),
            'name'=>$data['name'],
            'trades'=>$data['trades'],
            'province'=>$data['province']['name'],
            'city'=>$data['city']['name'],
            'area'=>$data['area']['name'],
            'address'=>$data['address'],
            'mobile'=>$data['mobile'],
            'captcha'=>$data['captcha'],
        ];
        $register = (new AutoUpdate())->registerFree($params);
        if(!is_null($register)){
            if (1 == $register['result']) {
                if ($register['data']) {
                    //检测数据是否存在
                    /*$res = $this->isExist($register['data']['shop']);
                    //var_dump($res);exit();
                    if (!$res['isExists']) {
                        if ($res['message'] == 'amount exceeded') {
                            $this->errorJson('您已经没有剩余站点数量了，如添加新站点，请取消之前的站点或者联系我们的客服人员！');
                        } else {
                            $this->errorJson('Key或者密钥出错了！');
                        }
                    } else {*/
                    if ($this->processingKey($register['data']['shop'], 'create')) {
                        if ($register['data']['plugins']) {
                            Setting::set('free.plugin', $register['data']['plugins']);
                        }
                        return $this->successJson("站点添加成功", ['url' => $auth_url]);
                    }
                    //}
                }
            }else{
                \Log::error('站点添加失败',$register);
                return $this->errorJson($register['msg']);
            }
        }
        return $this->errorJson("站点添加失败");
    }
    public function sendSms()
    {
        $domain = request()->getHttpHost();
        $mobile = request()->mobile;
        $res = (new AutoUpdate())->sendSms([
            'mobile'=>$mobile,
            'domain'=>$domain,
            ]);

        return $this->successJson('验证码已发送', $res);
    }
    public function resetAuth()
    {
        $data = request()->data;

        $setting = Setting::get('shop.key');

        if ($data['key'] && $data['secret']) {
            try {
                //todo 远端更新数据
                Setting::set('shop.key', $data);
            }  catch (\Exception $e) {
                return $this->errorJson($e->getMessage());
            }
        }

        return $this->successJson('成功', $setting);
    }
    /*
     * 处理信息
     */
    private function processingKey($requestModel, $type)
    {
        $domain = request()->getHttpHost();
        $data = [
            'uniacid' => 0,
            'key' => $requestModel['key'],
            'secret' => $requestModel['secret'],
            'domain' => $domain,
        ];
        $autoUpdate = new AutoUpdate();
        if ($type == 'create') {

            $content = $autoUpdate->appAccountCreate($data);
            // dd($content);exit();
            $writeRes = Setting::set('cms.auth', $requestModel);

            //\Cache::forget('app_auth' . $this->uniacid);

            return $writeRes && $content;

        } else if ($type == 'cancel') {

            $content = $autoUpdate->appAccountCancel($data);
            //var_dump($content);exit();

            $writeRes = Setting::set('shop.key', '');

            //\Cache::forget('app_auth' . $this->uniacid);

            return $writeRes && $content;
        }
    }
    /*
     * 检测是否有数据存在
     */
    public function isExist()
    {

        $type = request()->type;
        $domain = request()->getHttpHost();
        $postData = [
            'type' => $type,
            'domain' => $domain,
        ];
        $update = new AutoUpdate();
        $res = $update->isKeySecretExists($postData, 'auto_update ');
        return $res;
    }
}